package cn.wolfcode.shop.service.impl;

import cn.wolfcode.shop.domain.UserLnfo;
import cn.wolfcode.shop.domain.UserLogin;
import cn.wolfcode.shop.mapper.UserLnfoMapper;
import cn.wolfcode.shop.mapper.UserLoginMapper;
import cn.wolfcode.shop.service.IUserLoginService;
import cn.wolfcode.shop.utils.Assert;
import cn.wolfcode.shop.utils.MD5;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;

import java.text.MessageFormat;
import java.util.Date;

@Service
@Transactional
public class UserLoginServiceImpl implements IUserLoginService {
    @Autowired
    private UserLoginMapper userLoginMapper;
    @Autowired
    private UserLnfoMapper userLnfoMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 注册账号
     * @param username
     * @param password
     */
    @Override
    public UserLogin register(String username, String password) {
        //1.判断参数
        //2.保存用户账号密码
        UserLogin userLogin = new UserLogin();
        userLogin.setUserName(username);
        userLogin.setPassword(MD5.encode(password+username));

        userLoginMapper.insert(userLogin);

        //保存用户信息
        UserLnfo userLnfo = new UserLnfo();
        userLnfo.setRegistTime(new Date());
        userLnfo.setId(userLogin.getId());
        userLnfoMapper.insert(userLnfo);

        return userLogin;

    }

    /**
     * 登录接口
     * @param username
     * @param password
     */
    @Override
    public String login(String username, String password) {
        UserLogin userLogin = userLoginMapper.loginChecking(username,MD5.encode(password+username));
        Assert.notNull(userLogin,"账号或密码错误");
        //生成 key
        String token = MessageFormat.format("user:{0}", userLogin.getId());
        redisTemplate.opsForValue().set(token,userLogin);

        return token;
    }

    /**
     * 注销接口
     * @param token
     */
    @Override
    public void loginout(String token) {
        //清楚登陆信息缓存
        redisTemplate.delete(token);

    }
}
